package org;

import java.io.IOException;
import java.io.InputStream;

/**
 * javac ClassLoaderTest.java
 * cd ..
 * java org.ClassLoaderTest
 */
public class ClassLoaderTest {
    public static void main(String[] args) throws Exception {
        ClassLoader myLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                System.out.println("load: " + name);
                String filename = name.substring(name.lastIndexOf(".") + 1) + ".class";
                InputStream is = getClass().getResourceAsStream(filename);
                if (null == is) {
                    return super.loadClass(name);
                }

                try {
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new ClassNotFoundException(name);
                }
            }
        };

        Object obj = myLoader.loadClass("org.ClassLoaderTest").newInstance();
        System.out.println(obj.getClass().getName());
        System.out.println(obj instanceof ClassLoaderTest);
        /**
         output:
         load: org.ClassLoaderTest
         load: java.lang.Object
         load: java.lang.ClassLoader
         load: org.ClassLoaderTest$1
         org.ClassLoaderTest
         false
         */

    }
}